package cn.bytecollege.common.controller;

import cn.bytecollege.common.constant.Resource;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;

/**
 * 图片上传的控制器类
 */
@WebServlet(name = "UploadController", value = "/common/upload")
@MultipartConfig(location = Resource.UPLOAD_PATH)
public class UploadController extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Part part = request.getPart("file");
        String fileName = part.getSubmittedFileName();

        //获取扩展名
        String ext = fileName.substring(fileName.indexOf("."));
        //最终存入的名字
        String name = System.currentTimeMillis()+"goods"+ext;
        part.write(name);
        String path = request.getContextPath();
        String str = "{ \"errno\": 0,\"data\": [{\"url\": \""+path+"/common/show?name="+name+"\",\"alt\": \"\",\"href\": \"\"}]}";
        //向浏览器响应信息
        response.setContentType("application/json");
        response.getWriter().write(str);
    }
}
